/*
 * Copyright (C) 2011 Christopher Probst
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the 'FoxNet Codec' nor the names of its 
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.foxnet.codec;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author Christopher Probst
 */
public final class CodecBin {

    // Used if no codecs were found
    private static final Codec<?>[] EMPTY_CODECS = new Codec<?>[0];
    // Used to store the codec bindings
    private final Map<Class<?>, Codec<?>> codecMap = new HashMap<>();
    // The hierarchy codecs
    private final Map<Class<?>, Codec<?>[]> hierarchyMap = new HashMap<>();
    // All codec instances
    private final Codec<?>[] codecs;
    // All codec types
    private final Class<?>[] codecTypes;
    // The CodecSystem
    private final CodecRegistry codecRegistry;

    private void crawlInterfaces(Class<?> clazz, Set<Codec<?>> codecSet) {
	// Tmp codec var
	Codec<?> tmpCodec;

	for (Class<?> interfaceClass : clazz.getInterfaces()) {

	    // Check existing codecs
	    tmpCodec = codecMap.get(interfaceClass);

	    // Add codec to list
	    if (tmpCodec != null) {
		codecSet.add(tmpCodec);
	    }

	    // Check next
	    crawlInterfaces(interfaceClass, codecSet);
	}
    }

    CodecBin(CodecRegistry codecRegistry) throws InstantiationException,
	    IllegalAccessException {

	// Check for null
	if (codecRegistry == null) {
	    throw new NullPointerException("codecRegistry");
	}

	// Save the codec registry
	this.codecRegistry = codecRegistry;

	// Get the codec bindings
	for (Entry<Class<?>, Class<? extends Codec<?>>> binding : codecRegistry
		.getCodecBindings().entrySet()) {
	    // Try to load codec binding
	    codecMap.put(binding.getKey(), binding.getValue().newInstance());
	}

	// Create codecs
	codecs = codecMap.values().toArray(new Codec<?>[codecMap.size()]);

	// Create codec types
	codecTypes = codecMap.keySet().toArray(new Class<?>[codecMap.size()]);
    }

    public Codec<?>[] getCodecs() {
	return codecs;
    }

    public Class<?>[] getCodecTypes() {
	return codecTypes;
    }

    @SuppressWarnings("unchecked")
    public <T> Codec<T> getCodec(Class<T> clazz) {
	return (Codec<T>) codecMap.get(clazz);
    }

    @SuppressWarnings("unchecked")
    public <T> Class<T> getCodecType(Codec<T> codec) {
	if (codec == null) {
	    throw new NullPointerException("codec");
	}

	return codecRegistry
		.getCodecBindingType((Class<? extends Codec<T>>) codec
			.getClass());
    }

    public CodecRegistry getCodecRegistry() {
	return codecRegistry;
    }

    public Codec<?>[] getHierarchyCodecs(Class<?> clazz) {

	// Get the tmp hierarchy codecs
	Codec<?>[] codecs = hierarchyMap.get(clazz);

	if (codecs == null) {

	    // Create a hash set
	    final Set<Codec<?>> codecSet = new HashSet<Codec<?>>();

	    // Tmp crawler class var
	    Class<?> crawlerClass = clazz;

	    // Tmp codec var
	    Codec<?> tmpCodec;

	    do {
		// Check existing codecs
		tmpCodec = codecMap.get(crawlerClass);

		// Add codec to list
		if (tmpCodec != null) {
		    codecSet.add(tmpCodec);
		}

		// Crawl the interfaces
		crawlInterfaces(crawlerClass, codecSet);
	    } while ((crawlerClass = crawlerClass.getSuperclass()) != null);

	    if (!codecSet.isEmpty()) {
		// Create new array
		codecs = new Codec<?>[codecSet.size()];

		// Save in array
		codecSet.toArray(codecs);
	    } else {
		// Set empty codecs
		codecs = EMPTY_CODECS;
	    }

	    // Create new set
	    hierarchyMap.put(clazz, codecs);
	}

	return codecs;
    }
}
